const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const { name } = require('./package');
const defaultSettings = require('./src/settings.js');

function resolve(dir) {
  return path.join(__dirname, dir);
}

const webpageName = defaultSettings.title; // page title

const port = process.env.VUE_APP_PORT || 9527;
const publicPath = process.env.VUE_APP_PUBLIC_PATH;
const assetsDir = 'static';
module.exports = {
  publicPath,
  outputDir: 'dist',
  assetsDir,
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    open: false,
    overlay: {
      warnings: false,
      errors: true,
    },
    proxy: {
      // 接口代理
      [process.env.VUE_APP_BASE_API]: {
        target: `http://localhost:8097`,
        changeOrigin: true,
        pathRewrite: {
          [`^${process.env.VUE_APP_BASE_API}`]: '',
        },
      },
      '/minio/': {
        target: `http://10.10.10.20:9000`,
        changeOrigin: true,
        pathRewrite: {
          [`^/minio`]: '',
        },
      },
    },
    // before: require('./mock/mock-server.js'),
  },
  configureWebpack: {
    name: webpageName,
    devtool: 'source-map',
    output: {
      library: `${name}-[name]`,
      libraryTarget: 'umd',
      jsonpFunction: `webpackJsonp_${name}`,
    },
    resolve: {
      alias: {
        '@': resolve('src'),
      },
    },
    optimization: {
      // 此处添加 移除console.log 和 debugger的代码
      minimizer: [
        new UglifyJsPlugin({
          uglifyOptions: {
            output: {
              comments: false,
            },
            compress: {
              drop_console: true,
              drop_debugger: true,
              pure_funcs: ['console.log'],
            },
          },
        }),
      ],
    },
  },
  chainWebpack(config) {
    // 如果热更新失效，如下操作
    config.resolve.symlinks(true);
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial',
      },
    ]);

    config.plugins.delete('prefetch');
    // set svg-sprite-loader
    config.module.rule('svg').exclude.add(resolve('src/icons')).end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
        esModule: false,
        publicPath,
      })
      .end();
    // url-loader
    config.module
      .rule('fonts')
      .use('url-loader')
      .loader('url-loader')
      .options({
        esModule: false,
        limit: 4 * 1024, // 小于4kb的字体文件将会被打包成 base64
        fallback: {
          loader: 'file-loader',
          options: {
            name: `${assetsDir}/fonts/[name].[hash:8].[ext]`,
            test: /\.(woff2?|eot|ttf|otf)$/i,
            esModule: false,
            publicPath,
          },
        },
      })
      .end();
    config.module
      .rule('images')
      .use('url-loader')
      .loader('url-loader')
      .options({
        esModule: false,
        limit: 10 * 1024, // 小于10kb的图片将会被打包成 base64
        fallback: {
          loader: 'file-loader',
          options: {
            name: `${assetsDir}/img/[name].[hash:8].[ext]`,
            test: /\.(png|jpe?g|gif|webp)$/i,
            esModule: false,
            publicPath,
          },
        },
      })
      .end();

    config.when(process.env.NODE_ENV !== 'development', (config) => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            inline: /runtime\..*\.js$/,
          },
        ])
        .end();
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial',
          },
          elementUI: {
            name: 'chunk-elementUI',
            priority: 20,
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'),
            minChunks: 3,
            priority: 5,
            reuseExistingChunk: true,
          },
        },
      });
      config.optimization.runtimeChunk('single');
    });
  },
};
